<script setup>
  import { ref } from 'vue'
  import { addArticleChannelService, editArticleChannelService } from '@/api/article.js'

  const dialogVisible = ref(false)
  const formRef = ref()
  const formModel = ref({
    cate_name: '',
    cate_alias: ''
  })
  const rules = {
    cate_name: [
      { required: true, message: '请输入分类名称', trigger: 'blur' },
      { pattern: /^\S{1,10}$/, message: '分类名称必须是1-10个非空格字符', trigger: 'blur' }
    ],
    cate_alias: [
      { required: true, message: '请输入分类别名', trigger: 'blur' },
      { pattern: /^[A-Za-z0-9]{1,15}$/, message: '分类别名必须是1-15个字母或数字', trigger: 'blur' }
    ]
  }

  const emit = defineEmits(['success'])
  const handleSubmit = async () => {
    // 校验表单
    await formRef.value.validate()
    const isEdit = formModel.value.id
    if (isEdit) {
      // 编辑
      await editArticleChannelService(formModel.value)
      ElMessage.success('编辑成功')
    } else {
      // 添加
      await addArticleChannelService(formModel.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    emit('success')
  }

  // 组件对外暴露一个方法open,基于open传来的参数,区分是添加还是编辑
  // open({}) => 表单无需渲染,说明是添加
  // open({id: 1,...}) => 表单需要渲染,说明是编辑
  // open调用后,可以打开弹窗
  const open = (row) => {
    dialogVisible.value = true
    // 添加=>重置了表单内容,编辑=>存储了需要回显的数据
    formModel.value = { ...row }
  }
  // 向外暴露方法
  defineExpose({
    open
  })
</script>
<template>
  <el-dialog v-model="dialogVisible" :title="formModel.id ? '编辑分类' : '添加分类'" width="30%">
    <el-form
      :model="formModel"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="formModel.cate_name" placeholder="请输入分类名称"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="formModel.cate_alias" placeholder="请输入分类别名"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
